const F2 = require('../../../../component/ui/f2-canvas/lib/f2')
const api = require('../../../../wxapi/config.js')
Page({
	/**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '影视行业大数据',
      path: '/pages/index/inedx/index',
    }
  },
  data: {
    stars: 0,
    poster: {
      mc: '-',
      pf: '-',
      lx: '-',
      bj: '-',
      dy: '-',
      zpr: '-',
      url: ''
    },
    roleInfoList: [],
    busiId: '',
    mc: '',
    sourceType: '',
    isRoleInfoloading: true,
    haibaoimg: 'https://cdn.xtde.cn/wxapp/xtde/haibao.png',
    touxiang: 'https://cdn.xtde.cn/wxapp/xtde/touxiang.jpg',
    themeOpts1: {
      lazyLoad: true
    },
    themeOpts2: {
      lazyLoad: true
    },
    themeOpts3: {
      lazyLoad: true
    },
    themeItem1: {},
    themeItem2: {},
    hasthemeChartData: false,
    isthemeChartloading: true,
    ishistoryloading: true,
    historytableData: [],
    skeleton: [1, 2, 3],
    isActive: [
      { isActived: false },
      { isActived: false },
      { isActived: false },
      { isActived: false },
    ],

    bestTotal: [],
    isLoading: true,

    topData: [],
    topChartBoxH: 500,
    ratingTop: {
      lazyLoad: true
    },
    isTopDataLoading: true,

    istableloading: true,
    playDetail: {},
    playDate:[]
  },
  onLoad: function (options) {
		this.setData({
     sourceType: options.type,
    	mc: options.name,
    	busiId: options.id
    }) 
    this.getPoster(options.id)
    this.getRoleInfo(options.id)
  },
  toggleActive: function (e) {
    var _this = this
    let i = e.target.dataset.item
    let isActived = 'isActive[' + i + '].isActived';
    _this.setData({ [isActived]: !this.data.isActive[i].isActived });
  },
  // 切换基础信息/制作公司/卫视收视
  onChangeNav(event) {
    if (event.detail.index === 1 && this.data.historytableData.length === 0) {
      this.getHistory(this.data.mc)
      this.getThemeChart(this.data.mc)
    }
		if (event.detail.index === 2 && this.data.topData.length === 0) {
      this.getBestRatingTotal(this.data.busiId);
      this.getTopData(this.data.busiId)
      this.getPlayDetail(this.data.busiId)
    }
  },
  toActorDetailPage(e) {
    wx.navigateTo({
      url: '/pages/search/search-detail/actor-detail/actor-detail?id=' + e.currentTarget.dataset.roleid
    })
  },
  // 获取指定剧名的影片海报信息
  getPoster(id) {
    api.getTeleplayPosterList({ busiId: id }).then((res) => {
      if (res.data.length !== 0) {
        this.setData({
          poster: res.data[0],
          stars: (parseFloat(res.data[0].pf) / 2).toFixed(1)
        })
      } else {
        this.setData({
          poster: {
            mc: this.data.mc,
            pf: '-',
            lx: '-',
            bj: '-',
            dy: '-',
            zpr: '-',
            url: ''
          }
        })
      }
    })
  },
  // 获取角色信息
  getRoleInfo(teleId) {
    api.getTeleplayBaseInfo({ busiId: teleId }).then((res) => {
      this.setData({
        isRoleInfoloading: false
      })
      if (res.data.length !== 0) {
        this.setData({
          roleInfoList: res.data
        })
      } else {
        this.setData({
          roleInfoList: []
        })
      }
    })
  },
  getHistory(mc) {
    api.getMakeTeleplayHistoryList({ mc: mc }).then((res) => {
      this.setData({
        ishistoryloading: false
      })
      if (res.data.length !== 0) {
        this.setData({
          historytableData: res.data
        })
      } else {
        this.setData({
          historytableData: []
        })
      }
    })
  },
  // 获取题材占比
  getThemeChart(mc) {
    api.getTeleplayGenresRateList({ mc: mc }).then((res) => {
      this.setData({
        isthemeChartloading: false
      })
      if (res.data[0].plan.length !== 0 || res.data[0].release.length !== 0) {
        // console.log(res.data[0])
        this.setData({
          hasthemeChartData: false
        })
        if (res.data[0].plan.length !== 0) {
          this.setData({
            themeItem1: {
              name: res.data[0].plan[0].lx,
              total: parseInt(res.data[0].plan[0].total) * 100 + '%'
            }
          })
          var data1 = []
          for (let i in res.data[0].plan) {
            data1.push({
              name: res.data[0].plan[i].lx,
              total: parseInt(res.data[0].plan[i].total)
            })
          }
          this.pieSelectChart('compertheme1', data1, 0)
        }
        if (res.data[0].release.length !== 0) {
          this.setData({
            themeItem2: {
              name: res.data[0].release[0].lx,
              total: parseInt(res.data[0].release[0].total) * 100 + '%'
            }
          })
          var data2 = []
          for (let i in res.data[0].release) {
            data2.push({
              name: res.data[0].release[i].lx,
              total: parseInt(res.data[0].release[i].total)
            })
          }
          this.pieSelectChart('compertheme2', data2, 0)
        }
      } else {
        this.setData({
          themeItem1: '',
          themeItem2: '',
          hasthemeChartData: true
        })
      }
    })

  },
  //环状图
  pieSelectChart(id, data, type) {
    this.chartComponent = this.selectComponent('#' + id);
    this.chartComponent.init((canvas, width, height) => {
      var chart = new F2.Chart({
        el: canvas,
        width,
        height
      });
      chart.source(data, {
        percent: {
          formatter: function formatter(val) {
            return val * 100 + '%';
          }
        }
      });
      // chart.legend({
      // 	position: 'bottom',
      // 	align: 'center'
      // });
      chart.legend(false)
      chart.tooltip(false)
      chart.coord('polar', {
        transposed: true,
        radius: 0.95,
        innerRadius: 0.8
      });
      chart.axis(false)
      chart
        .interval()
        .position('a*total')
        .color('name')
        .adjust('stack')
        .style({
          lineWidth: 1,
          stroke: '#fff',
          lineJoin: 'round',
          lineCap: 'round'
        });

      chart.interaction('pie-select', {
        cancelable: false, // 不允许取消选中
        animate: {
          duration: 300,
          easing: 'backOut'
        },
        defaultSelected: {
          name: data[0].name,
          total: data[0].total * 100 + '%'
        },
        onEnd: (ev) => {
          const { shape, data, shapeInfo, selected } = ev;
          if (shape) {
            if (selected) {
              if (type === 0) {
                this.setData({
                  themeItem1: {
                    name: data.name,
                    total: data.total * 100 + '%'
                  }
                })
              }
              if (type === 1) {
                this.setData({
                  themeItem2: {
                    name: data.name,
                    total: data.total * 100 + '%'
                  }
                })
              }
            }
          }
        }
      });
      chart.render()
      return chart
    })
  },

  // 获取最佳收视
  getBestRatingTotal(tid) {
    api.getGoodRatingTotal({tid: tid}).then((res) => {
      if (res.data.length !== 0) {

				const data = res.data[0]
				data.sspdrq = data.spd ? data.spd : '--'
				data.srq = data.srq ? data.srq.replace(/-/g, "/") : '--'
				data.tbucket = data.tbucket ? data.tbucket : '--'
				data.szb = data.szb ? data.szb : '--'

        this.setData({
					bestTotal: data,
          isLoading: false
        })
      } else {
        this.setData({
          bestTotal: [],
          isLoading: false
        })
      }
    })
  },
  // 获取 收视排行TOP10 数据
  getTopData(tid) {
    api.getRankTopList({tid: tid}).then((res) => {
      if (res.data.length !== 0) {
        var data = []
        if (res.data.length > 10) {
          this.setData({
            topChartBoxH: 40 * res.data.length
          })
        }
        for (let i in res.data) {
          data.unshift({
            '频道': res.data[i].spd,
						'市场占有率': parseFloat(parseFloat(res.data[i].szb).toFixed(2))
          })
        }
        this.setData({
          topData: data,
          isTopDataLoading: false
        })
        this.initChart(data)
      } else {
        this.setData({
          topData: [],
          isTopDataLoading: false
        })
      }
    })
  },
  // 图表初始化
  initChart(data) {
    this.chartComponent = this.selectComponent('#ratingTop')
    this.chartComponent.init((canvas, width, height) => {
      const chart = new F2.Chart({
        el: canvas,
        width,
        height
      })
      var Global = F2.Global
      chart.source(data, {
        '卫视收视排行': {
          tickCount: 5
        }
      });
      chart.coord({
        transposed: true
      });
			chart.tooltip({
				alwaysShow: true,
				showCrosshairs: true,
				showItemMarker: false,
				onShow: function onShow(ev) {
					var items = ev.items;
					items[0].name = null;
					items[0].value = '市场占有率 （' + items[0].title + '） ' +items[0].value + '%';
				}
			})
      chart.axis('频道', {
        line: Global._defaultAxis.line,
        grid: null
      });
      chart.axis('市场占有率', {
        line: null,
        grid: Global._defaultAxis.grid,
        label: function label(text, index, total) {
          var textCfg = {};
          if (index === 0) {
            textCfg.textAlign = 'left'
          } else if (index === total - 1) {
            textCfg.textAlign = 'right'
          }
          return textCfg;
        }
      });
      
      chart.interval().position('频道*市场占有率').color('#0072ff')
      chart.render()
			// 初始化展示Tooltip
			var item = {
				'频道': (data[data.length -1])['频道'],
				'市场占有率': (data[data.length - 1])['市场占有率']
			}; 
			var point = chart.getPosition(item); 
			chart.showTooltip(point); 
      return chart
    })
  },
  // 获取 播放情况 数据
  getPlayDetail(tid) {
    api.getPlayDetailInfo({tid: tid}).then((res) => {
      if (Object.keys(res.data).length !== 0) {
        this.setData({
          playDetail: res.data,
          playDate: Object.keys(res.data),
          istableloading: false
        })
      } else {
        this.setData({
          palyDetail: {},
          playDate: [],
          istableloading: false
        })
      }
    })
  }
  
})